import Router from '@koa/router';
import logger from '../logger.js';
import response from '../response.js';
import { GetOpenID, getPhoneNumber } from '../common/wx.js';
import lsyPay from '../common/lsyPay.js';
import db from '../mysqlHelper.js';
import moment from 'moment';

const router = new Router();
router.prefix('/api');

router.post(`/applet/getOpenID`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await GetOpenID(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '获取OpenID成功');
});
router.post(`/applet/getPhoneNumber`, async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.code == null) {
        ctx.body = response.fail('缺少必填字段 code');
        return;
    }
    let res = await getPhoneNumber(body.code);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    if (typeof (res.data) == "string") {
        res.data = JSON.parse(res.data);
    }
    ctx.body = response.success(res.data, '获取手机号成功');
});

//创建预支付订单
router.post(`/applet/advance/createOrder`, async (ctx) => {
    let body = ctx.request.body;
    console.log('创建预支付订单', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.openid == null) {
        ctx.body = response.fail('缺少必填字段 openid');
        return;
    }
    if (body.plate == null) {
        ctx.body = response.fail('缺少必填字段 车牌号');
        return;
    }
    if (body.project_id == null) {
        ctx.body = response.fail('缺少必填字段 项目ID');
        return;
    }
    if (body.amount == null) {
        ctx.body = response.fail('缺少必填字段 充值金额');
        return;
    }
    if (body.phone == null) {
        ctx.body = response.fail('缺少必填字段 手机号');
        return;
    }
    if (body.pay_type == null) {
        body.pay_type = 0;
    }
    let tradeNo = "";
    if (body.pay_type == 0) {
        tradeNo = moment().format('YYMMDDHHmmss') + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    }



    if (body.order_body == null) {
        body.order_body = `${body.plate} 预支付`;
    }
    let sql = `select project.name, project.isp_id,isp.path from project join isp on project.isp_id=isp.id  where project.status =1 and project.id=${body.project_id}`;
    let project = await db.query(sql);
    if (project.length == 0) {
        ctx.body = response.fail('项目不存在或已关闭');
        return;
    }
    let userPayRecord = {
        openid: body.openid,
        plate: body.plate,
        isp_id: project[0].isp_id,
        project_id: body.project_id,
        pay_amt: body.amount,
        pay_status: 0,
        pay_type: body.pay_type,
        path: project[0].path,
        create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        pay_status: 0,
        pay_sn: moment().format('YYYYMMDDHHmmssSSS') + Math.floor(Math.random() * 1000000),
        phone: body.phone

    };
    if (body.pay_type == 0) {
        userPayRecord.tradeNo = tradeNo;
    }
    console.info('创建预支付订单', JSON.stringify(userPayRecord));
    if (body.vin != null) {
        userPayRecord.vin = body.vin;
    }
    if (body.nickname != null) {
        userPayRecord.nickname = body.nickname;
    }


    //创建支付订单
    let res = await lsyPay.applet_pay(userPayRecord.pay_sn, body.amount, body.openid, body.order_body);
    if (res.errMsg) {
        ctx.body = response.fail('创建支付订单出错:' + res.errMsg);
        return;
    }
    if (res.return_code != 'SUCCESS') {
        ctx.body = response.fail(res.return_msg);
        return;
    }
    let db_result = await db.create('user_pay_rec', userPayRecord);
    if (db_result instanceof Error) {
        ctx.body = response.fail('创建订单失败:' + db_result.message);
        return;
    }
    ctx.body = response.success(res, '创建订单成功', { tradeNo: tradeNo });
});
router.all(`/lsy/notify`, async (ctx) => {
    let body = ctx.request.body;
    console.info('接收到支付回调', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.result_code == 'PAY_SUCCESS') {
        //支付成功
        let order = await db.findOne('user_pay_rec', { pay_sn: body.pay_trace_no });
        if (order == null) {
            console.error('订单号错误，请使用正确的订单号', JSON.stringify(body));
            ctx.body = { return_code: "SUCCESS", return_msg: "订单号错误，请使用正确的订单号" };
            return;
        }
        order.pay_status = 10;
        order.pay_time = moment(body.pay_time, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
        let res = await db.update('user_pay_rec', order, { id: order.id });
        if (res instanceof Error) {
            console.error('更新订单状态失败', res.message, JSON.stringify(order));
            ctx.body = { return_code: "Fail", return_msg: "更新订单状态失败" };
            return;
        }
        console.info('更新订单状态成功', JSON.stringify(order));
        ctx.body = { return_code: "SUCCESS", return_msg: "成功" };
    }
    else {
        //支付失败
        console.error('接收到异常的支付回调', JSON.stringify(body));
        ctx.body = { return_code: "SUCCESS", return_msg: "成功" };
    }
});
//预支付订单退款
router.post(`/applet/advance/refund`, async (ctx) => {
    let body = ctx.request.body;
    console.log('预支付订单退款', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.pay_sn == null) {
        ctx.body = response.fail('缺少必填字段 订单号');
        return;
    }
    let pay_record = await db.findOne('user_pay_rec', { pay_sn: body.pay_sn });
    if (pay_record == null) {
        ctx.body = response.fail('订单不存在');
        return;
    }
    let phone = pay_record.phone;
    //检查是否有正在充电中的订单
    let isCharging = await db.checkExist('chargeing_order', { phone: phone,});
    if (isCharging) {
        ctx.body = response.fail('存在正在充电中的订单,不允许退款');
        return;
    }
    if (pay_record.pay_status != 10) {
        ctx.body = response.fail('订单状态不允许退款');
        return;
    }
    if (pay_record.pay_type == 0) //充电预充值订单
    {
        if (body.tradeNo != null) {
            let chargeing_order = await db.findOne('chargeing_order', { id: body.tradeNo });
            if (chargeing_order != null) {
                ctx.body = response.fail('订单正在充电中,不允许退款');
                return;
            }
        }
    } else if (pay_record.pay_type == 1) {
        //占位停车预充值
        ctx.body = response.fail('占位停车预充值不允许退款');
    }

    //退款操作
    let create_time = moment().format('YYYY-MM-DD HH:mm:ss');
    let refund_sn = lsyPay.generateTraceNo();
    let refund_res = await lsyPay.refund(refund_sn, pay_record.pay_amt, body.pay_sn);
    if (refund_res.code == 1) {
        logger.error(`退款失败`, `phone:${pay_record.phone}, refund_amt:${pay_record.pay_amt}, pay_sn:${body.pay_sn}`);
        ctx.body = response.fail(refund_res.msg);
        return;
    }
    console.log('退款结果', JSON.stringify(refund_res));
    //开始构建事务更新数据库
    let pay_status = 20;
    let refund_status = 10;
    if (refund_res.code == 2) refund_status = 0;
    //插入退款记录
    let refund_record = {
        phone: pay_record.phone,
        refund_amt:pay_record.pay_amt,
        refund_sn,
        refund_status,
        create_time,
        refund_type: 1, // 1:订单结束退款
        project_id: pay_record.project_id,
        isp_id: pay_record.isp_id,
        plate: pay_record.plate,
        openid: pay_record.openid,
    }
    if (refund_res.code == 0) {
        pay_status = 21;
        refund_record.refund_time = moment().format('YYYY-MM-DD HH:mm:ss');
    }
    let sqls = [];
    sqls.push({ sql: `update user_pay_rec set pay_status=${pay_status} where id=?`, param: [pay_record.id] });
    sqls.push({ sql: `insert into user_refund_rec set ?`, param: [refund_record] });
    let result = await db.transaction(sqls);
    if (result instanceof Error) {
        console.error('退款失败', result.message);
        ctx.body = response.fail('退款失败');
        return;
    }
    console.info('退款成功', JSON.stringify(refund_record));
    ctx.body = response.success(refund_record, '退款成功');
    return;
});






//接收退款支付回调 更新user_pay_rec的状态
router.all(`/lsy/notify/refund`, async (ctx) => {
    let body = ctx.request.body;
    console.info('接收到退款支付回调', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.result_code == 'TRADE_REFUND') {
        //退款成功
        let order = await db.findOne('user_pay_rec', { pay_sn: body.attach });
        if (order == null) {
            console.error('订单号错误，请使用正确的订单号', JSON.stringify(body));
            ctx.body = { return_code: "SUCCESS", return_msg: "订单号错误，请使用正确的订单号" };
            return;
        }
        //order.pay_status=31;
        // refund_sn=body.pay_trace_no;
        // order.refund_time=  moment(body.pay_time,'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss');
        //修改退款记录状态
         let sqls = [];
         sqls.push({ sql: `update user_refund_rec set refund_status=10 ,refund_time=? where refund_sn=?`, param: [moment().format('YYYY-MM-DD HH:mm:ss'), body.pay_trace_no] });
        sqls.push({ sql: `update user_pay_rec set pay_status=31 where id=?`, param: [order.id] });
        let result = await db.transaction(sqls);
        if (result instanceof Error) {
            console.error('更新退款和订单状态失败', result.message, JSON.stringify(order));
            ctx.body = { return_code: "Fail", return_msg: "更新退款和订单状态失败" };
            return;
        }
        console.info('更新退款和订单状态成功', body.pay_trace_no);
        ctx.body = { return_code: "SUCCESS", return_msg: "成功" };
    }
    else {
        //退款失败
        console.error('接收到异常的退款支付回调', JSON.stringify(body));
        ctx.body = { return_code: "SUCCESS", return_msg: "成功" };
    }
});
//提现回调
router.all(`/lsy/notify/enchash`, async (ctx) => {
    let body = ctx.request.body;
    console.info('接收到提现回调', JSON.stringify(body));
    ctx.body = { return_code: "SUCCESS", return_msg: "成功" };

});



//分页查询商户提现记录表
router.post(`/merchant/withdraw/page`, async (ctx) => {
    let body = ctx.request.body;
    console.log('分页查询商户提现记录表', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.merchant_no == null) {
        ctx.body = response.fail('缺少必填字段 merchant_no');
        return;
    }
    let res = await lsyPay.getMerchantWithdrawPage(body);
    if (res.code == 1) {
        ctx.body = response.fail(res.msg);
        return;
    }
    ctx.body = response.success(res.data, '查询成功');
})

//查询商户余额
router.post(`/merchant/balance`, async (ctx) => {
    let body = ctx.request.body;
    console.log('查询商户余额', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.merchant_no == null) {
        
        ctx.body = response.fail('缺少必填字段 merchant_no');
        return;
    }
    let balance = await lsyPay.getMerchantBalance(body.merchant_no);
    if (balance.code!= 0) {
        ctx.body = response.fail(balance.msg);
        return;
    }
    ctx.body = response.success({balance:balance.balance}, '查询成功');
})
//商户发起手动提现
router.post(`/merchant/withdraw/request`, async (ctx) => {
    let body = ctx.request.body;
    console.log('商户发起手动提现', JSON.stringify(body));
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.merchant_no == null) {
        ctx.body = response.fail('缺少必填字段 merchant_no');
        return;
    }
    if (body.amount == null) {
        ctx.body = response.fail('缺少必填字段 amount');
        return;
    }
    let balance = await lsyPay.getMerchantBalance(body.merchant_no);
    if (balance.code!= 0) {
        ctx.body = response.fail(balance.msg);
        return;
    }
    if (balance.balance < body.amount) {
        ctx.body = response.fail('提现金额大于可用余额');
        return;
    }
    let withdraw_result  = await lsyPay.merchantWithdraw(body.merchant_no, body.amount);
    if (withdraw_result.code> 0) {
        ctx.body = response.fail(withdraw_result.msg);
        return;
    }
    ctx.body = response.success(withdraw_result.data, '手动提现成功');
})


export { router };
